package com.huajin.gateway.flow.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huajin.gateway.flow.domain.NetPackage;
import com.huajin.gateway.flow.service.NetPackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.groupingBy;

@Service
public class NetPackageServiceImpl implements NetPackageService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Map<String, List<NetPackage>> getNetPackageGroupByDstPort() throws IOException {

        String key = "netflow";
        long size = redisTemplate.opsForList().size(key);
        List<String> list = redisTemplate.opsForList().range(key, 0, size);
        ObjectMapper objectMapper = new ObjectMapper();
        List<NetPackage> netPackageList = new ArrayList<>();
        for (String netflow : list) {
            NetPackage netPackage = null;
            netPackage = objectMapper.readValue(netflow, NetPackage.class);
            netPackageList.add(netPackage);
        }

        Map<String, List<NetPackage>> result = netPackageList.stream().collect(groupingBy(NetPackage::getDstPort));
        return result;
    }
}
